import backtrader as bt
import numpy as np
import numpy as np
import pandas as pd
#乖离率
class bias_ind (bt.Indicator):
    lines = ('bias24',)
    def __init__(self, wave_window,data):
        self.params.wave_window = wave_window
        value_list = data.get(ago = data.buflen(), size = data.buflen())
        self.bias_24_value = self.getwave( value_list)
        # 这个很有用，会有 not maturity生成  设置了开始的位置
        # self.addminperiod(self.params.wave_window * 2)

    def getwave(self,value_list):
        try:
            # 计算方法：
            # bias指标
            # N期BIAS=(当日收盘价-N期平均收盘价)/N期平均收盘价*100%
            bias = []
            df = pd.DataFrame(value_list, columns=['close'])
            df['bias_6'] = (df['close'] - df['close'].rolling(6, min_periods=1).mean()) / df['close'].rolling(6,min_periods=1).mean() * 100
            df['bias_12'] = (df['close'] - df['close'].rolling(12, min_periods=1).mean()) / df['close'].rolling(12,min_periods=1).mean() * 100
            df['bias_24'] = (df['close'] - df['close'].rolling(24, min_periods=1).mean()) / df['close'].rolling(24,min_periods=1).mean() * 100
            df['bias_6'] = round(df['bias_6'], 2)
            df['bias_12'] = round(df['bias_12'], 2)
            df['bias_24'] = round(df['bias_24'], 2)
            bias_24=df.bias_24
            for i in range(0, len(bias_24.index)):
                bias.append(bias_24[i])
            #print(bias)
            '''
              for i in range(0, len(df.index)):
                if i > self.p.wave_window:
                    bias.append(np.std(np.log(df_close[i - self.p.wave_window:i] / df_close[i - self.p.wave_window:i].shift(-1))) * np.sqrt(252) * 100)
                else:
                    bias.append(df[i - self.p.wave_window:i])
            
            
            df_close = stockdata.close / stockdata.close[0]
            for i in range(0, len(stockdata.index)):
                if i > self.p.wave_window:
                    wave.append(np.std(np.log(df_close[i - self.p.wave_window:i] / df_close[i - self.p.wave_window:i].shift(-1))) * np.sqrt(252) * 100)
                else:
                    wave.append(0)
            '''
            return bias_24
        except Exception as e:
          1 + 1

    def next(self):
       try:
        num =len(self.bias24)#当前位置
        self.lines.bias24[0] = self.bias_24_value[num-1]
       except Exception as e:
        1 + 1